package unit10;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Ex10_6_TestActionEvent extends JFrame implements ActionListener {
    //声明成员变量
    private JButton yellowButton = new JButton("Yellow");
    private JButton blueButton = new JButton("Blue");
    private JButton redButton = new JButton("Red");
    //无参构造方法
    public Ex10_6_TestActionEvent() {
        //设置窗体标题
        setTitle("事件测试窗体");
        JPanel jpanel = new JPanel();
        jpanel.setLayout(new FlowLayout());
        //在面板中添加
        jpanel.add(yellowButton);
        jpanel.add(blueButton);
        jpanel.add(redButton);
        add(jpanel);
        //注册监听器
        yellowButton.addActionListener(this);
        blueButton.addActionListener(this);
        redButton.addActionListener(this);
    }
    // 当按钮被点击时，该方法将会被触发执行
    public void actionPerformed(ActionEvent e) {
        //当前事件源为yellowButton
        if (e.getSource() == yellowButton) {
            yellowButton.setBackground(Color.YELLOW);
        } else if (e.getSource() == blueButton) {//当前事件源为blueButton
            blueButton.setBackground(Color.BLUE);
        } else if (e.getSource() == redButton) {//当前事件源为redButton
            redButton.setBackground(Color.RED);
        }
    }

    // 主方法
    public static void main(String[] args) {
        Ex10_6_TestActionEvent frame = new Ex10_6_TestActionEvent();
        frame.setSize(300, 200);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

}
